package gloridifice.watersource.client.render.tile;

import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.vertex.IVertexBuilder;
import gloridifice.watersource.common.tile.WaterDispenserDownTile;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.texture.AtlasTexture;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.tileentity.TileEntityRenderer;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;

public class WaterDispenserTER extends TileEntityRenderer<WaterDispenserDownTile> {
    public WaterDispenserTER(TileEntityRendererDispatcher dispatcher) {
        super(dispatcher);
    }

    @Override
    public void render(WaterDispenserDownTile waterDispenserDownTile, float v, MatrixStack matrixStack, IRenderTypeBuffer iRenderTypeBuffer, int i, int i1) {
        Minecraft mc = Minecraft.getInstance();
        IFluidHandler fluidHandler = waterDispenserDownTile.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY).orElse(null);
        IVertexBuilder buffer = iRenderTypeBuffer.getBuffer(RenderType.getTranslucentNoCrumbling());
        TextureAtlasSprite still = mc.getAtlasSpriteGetter(AtlasTexture.LOCATION_BLOCKS_TEXTURE).apply(fluidHandler.getFluidInTank(0).getFluid().getFluid().getAttributes().getStillTexture());
        int colorRGB = fluidHandler.getFluidInTank(0).getFluid().getAttributes().getColor();
        float height = waterDispenserDownTile.getHeight();
        add(buffer, matrixStack, -0.0625f, 0.125f, 1f, still.getMinU(), still.getMinV(), colorRGB, 1.0f);
        add(buffer, matrixStack, 0.0625f, 0.125f, 1f, still.getMinU(), still.getMaxV(), colorRGB, 1.0f);
        add(buffer, matrixStack, -0.0625f, 0.125f + height, 1f, still.getMaxU(), still.getMinV(), colorRGB, 1.0f);
        add(buffer, matrixStack, 0.0625f, 0.125f + height, 1f, still.getMaxU(), still.getMaxV(), colorRGB, 1.0f);
    }
    private void add(IVertexBuilder renderer, MatrixStack stack, float x, float y, float z, float u, float v, int RGBA, float alpha) {
        float red = ((RGBA >> 16) & 0xFF) / 255f;
        float green = ((RGBA >> 8) & 0xFF) / 255f;
        float blue = ((RGBA >> 0) & 0xFF) / 255f;
        renderer.pos(stack.getLast().getMatrix(), x, y, z).color(red, green, blue, alpha).tex(u, v).lightmap(0, 240).normal(0, 0, 0).endVertex();
    }
}
